<template>
  <div>
    <!-- 菜品销售情况 -->
    <h2>{{ chartTitles.dishSales }}</h2>
    <el-card shadow="hover">
      <!-- 替换表格为图表容器 -->
      <div ref="chartRef" style="width: 100%; height: 400px;"></div>
    </el-card>

    <!-- 商家总收入 -->
    <h2>{{ chartTitles.totalIncome }}</h2>
    <el-card shadow="hover">
      <p>总收入：<strong>{{ totalIncomeData.totalIncome }}</strong></p>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import * as echarts from 'echarts'; // 引入echarts
import { ElMessage } from "element-plus";
import axios from 'axios';
import storage from "../../../storage.ts";
import {useRoute} from "vue-router";
const shopId = localStorage.getItem('shopInfo') ? JSON.parse(localStorage.getItem('shopInfo')).id : null;
const shop = ref({
    id: shopId,
    shopname: "",
    pwd: "",
    phone: "",
    address: "",
    picture: "",
    checked: "",
    state: "",
    income: "",
    score: ""
})

// 定义响应式数据
const dishSalesData = ref([]);
const totalIncomeData = ref({
    totalIncome: 0
});

// 图表标题
const chartTitles = {
  dishSales: '菜品销售情况',
  totalIncome: '商家总收入'
};

// 定义图表容器引用
const chartRef = ref<HTMLElement | null>(null);

// 渲染图表的方法
const renderChart = () => {
  if (!chartRef.value) return;
  
  const chart = echarts.init(chartRef.value);
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dishSalesData.value.map(item => item.dishName),
      axisLabel: {
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '销量'
    },
    series: [{
      name: '菜品销量',
      type: 'bar',
      data: dishSalesData.value.map(item => item.salesCount),
      itemStyle: {
        color: '#5470c6'
      },
      label: {
        show: true,
        position: 'top'
      }
    }]
  };
  
  chart.setOption(option);
  
  // 响应式调整图表大小
  window.addEventListener('resize', () => {
    chart.resize();
  });
};

// 数据获取方法
const fetchData = async () => {
    try {
        const dishSalesResponse = await axios.get('/api/income/dish-sales/' + shopId);
        const totalIncomeResponse = await axios.get('/api/income/total-income/' + shopId);

        // 检查 dishSalesResponse.data.data 是否存在且不为 null
        if (dishSalesResponse.data && dishSalesResponse.data.data) {
            dishSalesData.value = Object.entries(dishSalesResponse.data.data).map(([dishName, salesCount]) => ({
                dishName,
                salesCount
            }));
        } else {
            console.warn('Dish sales data is empty or null');
            dishSalesData.value = [];
        }

        // 检查 totalIncomeResponse.data.data 是否存在且不为 null
        if (totalIncomeResponse.data && totalIncomeResponse.data.data && totalIncomeResponse.data.data.totalIncome !== undefined) {
            totalIncomeData.value = {
                totalIncome: totalIncomeResponse.data.data.totalIncome
            };
        } else {
            console.warn('Total income data is empty or null');
            totalIncomeData.value = {
                totalIncome: 0
            };
        }

        // 在获取数据后，使用nextTick确保DOM更新后再渲染图表
        nextTick(() => {
            renderChart();
        });

    } catch (error) {
        console.error('数据加载失败:', error);
    }
};
const route = useRoute();

const user = ref();
// 生命周期钩子：组件挂载后调用 fetchData
onMounted(async () => {


    user.value = storage.getUser();
    storage.removeUser();
    try {
        // 优先从路由参数中获取店铺ID
        const shopId = route.query.id;
        if (shopId) {
            // 调用后端接口获取店铺信息
            const {data} = await axios.get(`/api/shop/${shopId}`);
            shop.value = data;
            console.log(shop.value);

        } else {
            // 如果没有路由参数，则尝试从localStorage中获取
            const storedShopInfo = localStorage.getItem('shopInfo');
            if (storedShopInfo) {
                shop.value = JSON.parse(storedShopInfo);

            }
        }
    } catch (error) {
        console.error('获取店铺信息失败:', error);
    }
     await fetchData();
})
</script>